package com.wsc.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wsc.entity.ConsumeLog;
import com.wsc.entity.Student;
import com.wsc.entity.Teacher;
import com.wsc.repository.ConsumeLogRepository;
import com.wsc.repository.StudentRepository;
import com.wsc.repository.SwipingCardRepository;
import com.wsc.repository.TeacherRepository;
import com.wsc.service.SwipingCardService;

@Service
@Transactional
public class SwipingCardServiceImpl implements SwipingCardService {

	@Autowired
	private ConsumeLogRepository cr;

	@Autowired
	private SwipingCardRepository sr;

	@Autowired
	private TeacherRepository tear;

	@Autowired
	private StudentRepository stur;

	/***
	 * 同一天、同意卡号、统一阅览室只能有一条刷卡记录 ;离开时间默认为进入时间10分钟后 ;再次刷卡更新离开时间；资源使用统计
	 */
	/****
	 * 通过卡号、阅览室编号、状态判断是否为第二次刷卡（刷出） 是：判断刷出时间是否大于默认刷出时间（刷入时间的10分钟后）， 是：修改刷出时间，修改状态为0
	 * 否：不修改刷出时间，修改状态 否：新建实体类对象，添加
	 */
	@Override
	public Map<String, Object> swipingCard(Map<String, Object> map) {
		// 卡号
		String cardno = (String) map.get("cardno");
		// 阅读室编号
		Integer readroomid = (Integer) map.get("readroomid");
		// 通过卡号查询教师或者学生
		Student s = stur.findByCardno(cardno);
		Teacher t = tear.findByCardno(cardno);
		// 查询不为null，为第二次刷卡（即为刷出）
		ConsumeLog c = cr.getOneByCardnoReadroomid(cardno, readroomid);
		if (c == null) {// 刷进
			swipingCardFirst(cardno, readroomid,s,t);
			map.put("code", 1);
		} else {// 刷出
			swipingCardSecond(cardno, readroomid, c,s,t);
			map.put("code", 2);
		}
		return map;
	}

	// 刷进
	public void swipingCardFirst(String cardno, Integer readroomid, Student s, Teacher t) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 当前进入时间
		String intime = sdf.format(new Date());
		// 默认离开时间为10分钟后
		long currentTime = System.currentTimeMillis() + 10 * 60 * 1000;
		String outtime = sdf.format(new Date(currentTime));
		ConsumeLog cEntity = new ConsumeLog(null, cardno, readroomid, intime, outtime, 1);
		// 添加数据
		cr.save(cEntity);
		// 修改学生或者教师的状态为资源编号
		if (t != null) {
			t.setStatus(readroomid);
			tear.save(t);
		} else {
			s.setStatus(readroomid);
			stur.save(s);
		}
	}
	// 刷出
	public void swipingCardSecond(String cardno, Integer readroomid, ConsumeLog c, Student s, Teacher t) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 当前进入时间
		String intime = sdf.format(new Date());
		// 刷卡离开时间
		c.setOuttime(sdf.format(new Date()));
		c.setStatus(0);
		// 修改
		cr.save(c);
		// 修改学生或者教师的状态为0
		if (t != null) {
			t.setStatus(0);
			tear.save(t);
		} else {
			s.setStatus(0);
			stur.save(s);
		}
	}
}
